from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models.medicine_model import Medicine
from schemas.medicine_schemas import MedicineCreate, MedicineUpdate,MedicineNameRequest
from services.auth_service import require_user

from models.user_models import *

router = APIRouter()


# 查询获取所有药品信息
@router.get("/medicines")
def get_pharmacists(db: Session = Depends(get_db),
                    user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR,UserType.PHARMACIST))):
    try:
        medicines = db.query(Medicine).all()
        return medicines
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/medicines")
def create_medicine(medicine: MedicineCreate, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    """
    创建新的药品记录
    """
    try:
        medicine.check()
    except ValueError:
        raise HTTPException(status_code=400, detail="传入MedicineCreate模型的值有误")

    #此处不用插入account数据
    db_medicine = Medicine(
        medicine_name=medicine.medicine_name,
        main_indications=medicine.main_indications,
        stock=medicine.stock,
        batch=medicine.batch,
        expiry_date=medicine.expiry_date,
        supplier=medicine.supplier,
        price=medicine.price,
        unit=medicine.unit,
    )
    db.add(db_medicine)
    db.commit()
    db.refresh(db_medicine)
    return db_medicine



@router.get("/medicines/{medicine_id}")
def read_medicine(medicine_id: int, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    """
    根据ID获取单个药品信息
    """
    db_medicine = db.query(Medicine).filter(Medicine.ID == medicine_id).first()
    if db_medicine is None:
        raise HTTPException(status_code=404, detail="Medicine not found")
    return db_medicine  

@router.post("/serach_medicine")
def get_medicines_by_name(request: MedicineNameRequest, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST,UserType.DOCTOR))):
    """
    根据药品名称获取所有匹配的药品记录，用于药剂师查询药品,药品名称用json传送
    """
    try:
        medicines = db.query(Medicine).filter(Medicine.medicine_name == request.medicine_name).all()
        if not medicines:
            raise HTTPException(status_code=404, detail="No medicines found with the given name")
        return medicines
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/medicines/{medicine_id}")
def update_medicine(medicine_id: int, medicine: MedicineUpdate, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    """
    更新药品信息
    """
    db_medicine = db.query(Medicine).filter(Medicine.ID == medicine_id).first()
    if db_medicine is None:
        raise HTTPException(status_code=404, detail="Medicine not found")
    
    update_data = medicine.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_medicine, key, value)
    
    db.add(db_medicine)
    db.commit()
    db.refresh(db_medicine)
    return db_medicine

@router.delete("/medicines/{medicine_id}")
def delete_medicine(medicine_id: int, db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PHARMACIST))):
    """
    删除药品记录
    """
    db_medicine = db.query(Medicine).filter(Medicine.ID == medicine_id).first()
    if db_medicine is None:
        raise HTTPException(status_code=404, detail="Medicine not found")
    
    db.delete(db_medicine)
    db.commit()
    return {"message": "Medicine deleted successfully"}